import * as types from '../mutation-types';
import { fetch } from 'utils/api.js';

const state = {
  loading: false,
  articleList: [],
  editingData: {},
  editMode: false
};

const mutations = {
  // 设置待修改内容(根据ID)
/*  [types.SET_ARTICLE_EDITING_ID](state, id) {
    state.editingData = state.articleList.find((article) => { return article.id == id; });
  },*/

  // 设置待修改内容(直接设置内容)
  [types.SET_ARTICLE_EDITING_DATA](state, editingData) {
    Object.assign(state.editingData, editingData);
  },
  // 是否进入修改模式(向编辑器填入editingdata)
  [types.SET_ARTICLE_ALT_MODE](state, isAltMode) {
    state.editMode = !!isAltMode;
  },
  // 从state中删除文章
/*  [types.DEL_LOCAL_ARTICLE](state, articleId) {
    let idx = state.articleList.findIndex((article) => article.id == articleId);
    if (idx >= 0) {
      state.articleList.splice(idx, 1);
    }
  },*/
  [types.CLEAR_EDIT_STATE](state) {
    state.editMode = false;
    state.editingData = {};
  },
  [types.ARTICLE_SET_TEMP_DATA](state, formData) {
    Object.assign(state.editingData, formData);
  },
};

const actions = {
  articleLoadInfo({ dispatch, commit, state }, id) {
    return new Promise((resolve, reject) => {
      fetch('articleInfo', { body: { id: id } }).then((res) => {
        if (res.code !== 200) {
          alert('抱歉，获取信息失败>_<');
          reject();
        }
        commit(types.SET_ARTICLE_ALT_MODE, true);
        commit(types.SET_ARTICLE_EDITING_DATA,res.data);
        resolve(res);
      }).catch((e) => {
        reject(e);
      });
    });
  },
  articleSetTempData({commit}, formData) {
    commit(types.ARTICLE_SET_TEMP_DATA, formData);
  },
  deleteArticle({ dispatch, commit, state }, id) {
    return new Promise((resolve, reject) => {
      fetch('deleteContent', { body: {id: id}}).then((res) => {
        if (res.code == 200){
          //commit(types.DEL_LOCAL_ARTICLE, id);
          resolve(res);
        }
      }).catch((e) => {
        reject(e);
      });
    });
  },
  publishArticle({ commit, state }) {
    return new Promise((resolve, reject) => {
      fetch('saveArticle', {
        body: state.editingData
      }).then((res) => {
        if (res.code == 200) {
          alert('发表成功');
          commit(types.CLEAR_EDIT_STATE);
          resolve(true);
        } else {
          alert(res.message);
          // commit(types.CLEAR_EDIT_STATE);
          reject(res.message);
        }
      },()=>{
        alert('抱歉，由于网络或服务器原因发表失败');
      });
    });
  }
};

export default {
  state,
  mutations,
  actions
};
